package com.kifas.service.dataaccess;

import java.util.List;

import javax.persistence.NoResultException;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.kifas.entity.UserEntity;
import com.kifas.utils.PasswordHelper;

@Repository
public class UserDao {

	private static final String VALIDATE_USER = "from UserEntity u where u.username = :username and u.password = :password";

	private static final String GET_USER = "from UserEntity u where u.username = :username";
	
	private static final String ALL_USER = "from UserEntity u";

	@Autowired
	private SessionFactory sessionFactory;

	public void insert(UserEntity user) throws Exception {
		user.setSecretCode(PasswordHelper.getPassword(user.getSecretCode()));
		sessionFactory.getCurrentSession().save(user);
	}

	public boolean getUserValidation(String username, String password) {
		try {
			sessionFactory.getCurrentSession().createQuery(VALIDATE_USER)
					.setString("username", username)
					.setString("password", password).uniqueResult();
		} catch (NoResultException e) {
			return false;
		}
		return true;
	}

	public void update(UserEntity user) throws Exception {
		UserEntity userEntity = (UserEntity) sessionFactory.getCurrentSession()
				.createQuery(GET_USER)
				.setString("username", user.getUsername()).uniqueResult();
		if (PasswordHelper.getPassword(user.getSecretCode()) != null) {
			userEntity.setEmail(user.getEmail());
			userEntity.setFirstName(user.getFirstName());
			userEntity.setLastName(user.getLastName());
			userEntity.setSecretCode(PasswordHelper.getPassword(user.getSecretCode()));
			userEntity.setGroups(user.getGroups());
			sessionFactory.getCurrentSession().update(userEntity);
		}
	}

	public UserEntity getUserById(String username) {
		return (UserEntity) sessionFactory.getCurrentSession().createQuery(GET_USER).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	public List<UserEntity> getUsers() {
		return sessionFactory.getCurrentSession().createQuery(ALL_USER).list();
	}
	
}
